﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NPOI;
using NPOI.HSSF;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;

namespace RenShiKaoQin.Account
{
    public partial class StudyRequest : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                hrdbEntities ent = new hrdbEntities();
                var result = from emp in ent.TEmployees where emp.FEmployeeID.Equals(Page.User.Identity.Name) select emp;
                TEmployee employee = result.Single();
                TDept dept = employee.TDepts.OrderBy(p => p.FValidDate).Last();
                lbName.Text = employee.FName;
                var rdept = from tdept in ent.TDictDepts where tdept.FDeptCode.Equals(dept.FKQDeptCode) select tdept;
                try
                {
                    lbDept.Text = rdept.Single().FName;
                    //lbDept.ID = rdept.Single().FDeptCode;
                    hfDeptCode.Value = rdept.Single().FDeptCode;
                    var rindept = from tindept in ent.TDictDepts where tindept.FDeptCode.Equals(dept.FDeptCode) select tindept;
                    lbInDept.Text = rindept.SingleOrDefault().FName;
                }
                catch
                {
                    Response.Write("您还没有所属科室或者考勤科室，请联系人事处");
                    Response.End();
                }
                lbGender.Text = employee.TDictGender != null ? employee.TDictGender.FName : "未知";
                if (employee.THeadShips.Any())
                {
                    THeadShip headShip = employee.THeadShips.OrderBy(p => p.FValidDate).Last();
                    lbHeadShip.Text = headShip.TDictHeadShip.FName;
                }
                else
                {
                    lbHeadShip.Text = "无";
                }

                if (employee.TTitles.Any())
                {
                    TTitle title = employee.TTitles.OrderBy(p => p.FValidDate).Last();
                    lbZhiChen.Text = title.TDictTitle.FName;
                }
                else
                {
                    lbZhiChen.Text = "无";
                }

                if (employee.TEngageJobs.Any())
                {
                    TEngageJob job = employee.TEngageJobs.OrderBy(p => p.FValidDate).Last();
                    lbGangWei.Text = job.TDictTitle.FName;
                }
                else
                {
                    lbGangWei.Text = "无";
                }
                lbTel.Text = employee.FMobileTel;
                lbBirthday.Text = employee.FBirthday.HasValue ? String.Format("{0:D}", employee.FBirthday.Value) : "";

                hfIntoHisDate.Value = employee.FIntoHisDate.HasValue ? employee.FIntoHisDate.Value.ToString("D") : "";
                hfFirstJobDate.Value = employee.FFirstWorkDate.HasValue ? employee.FFirstWorkDate.Value.ToString("D") : "";
                ent.Dispose();
            }

            sqlSR.SelectParameters.Clear();
            sqlSR.SelectParameters.Add("FEmployeeID", Page.User.Identity.Name);
            tbStart.Attributes["readonly"] = "readonly";
        }

        protected void btnApply_Click(object sender, EventArgs e)
        {
            if (tbCollage.Text == "" || tbSpeciality.Text == "" || tbStart.Text == "")
            {
                return;
            }
            using (hrdbEntities ent = new hrdbEntities())
            {
                DateTime startDate = DateTime.Parse(tbStart.Text);
                DateTime intoHisDate = DateTime.Parse(hfIntoHisDate.Value);
                if (intoHisDate.AddYears(3) < startDate)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "notEnoughYears", "alert('您必须工作满三年才能提出学习申请');", true);
                }                
                TKQStudyRequest sr = TKQStudyRequest.CreateTKQStudyRequest(0, Page.User.Identity.Name, hfDeptCode.Value, tbCollage.Text, tbSpeciality.Text, startDate, ddlEduLevel.SelectedValue, ddlDegree.SelectedValue, ddlEduType.SelectedValue);
                sr.EduStory = tbEduStory.Text;
                sr.ResearchStory = tbResearchStory.Text;
                sr.Reason = tbReason.Text;
                ent.TKQStudyRequests.AddObject(sr);
                ent.SaveChanges();
            }
            gvSR.DataBind();
            ExportByTemplate(null);
        }
        protected void ExportByTemplate(string type)
        {
            string physicalRoot = HttpContext.Current.Server.MapPath("/QJ");
            string physicalPath = physicalRoot + "/Templates/";
            HSSFWorkbook wb = null;
            string template = null;
            ISheet sheet1 = null;
            template = physicalPath + "在职人员攻读学历学位申请.xls";
            try
            {
                FileStream fs = new FileStream(template, FileMode.Open, FileAccess.Read);
                wb = new HSSFWorkbook(fs);
            }
            catch (IOException)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "FailtoGenerate", "alert('服务器正忙，请稍后再试');", true);
                return;
            }
            sheet1 = wb.GetSheet("在职人员");
            IRow row = sheet1.GetRow(1);
            row.Cells[1].SetCellValue(lbName.Text);
            row.Cells[1].CellStyle.Alignment = HorizontalAlignment.CENTER;
            row.Cells[3].SetCellValue(lbGender.Text);
            row.Cells[3].CellStyle.Alignment = HorizontalAlignment.CENTER;
            row.Cells[5].SetCellValue(lbBirthday.Text);
            row.Cells[5].CellStyle.Alignment = HorizontalAlignment.CENTER;
            row = sheet1.GetRow(2);
            row.Cells[1].SetCellValue(lbDept.Text);
            row.Cells[1].CellStyle.Alignment = HorizontalAlignment.CENTER;
            row.Cells[3].SetCellValue(lbZhiChen.Text);
            row.Cells[3].CellStyle.Alignment = HorizontalAlignment.CENTER;
            row.Cells[5].SetCellValue(lbHeadShip.Text);
            row.Cells[5].CellStyle.Alignment = HorizontalAlignment.CENTER;
            row = sheet1.GetRow(3);
            row.Cells[1].SetCellValue(hfFirstJobDate.Value);
            row.Cells[1].CellStyle.Alignment = HorizontalAlignment.CENTER;
            row.Cells[4].SetCellValue(hfIntoHisDate.Value);
            row.Cells[4].CellStyle.Alignment = HorizontalAlignment.CENTER;
            row = sheet1.GetRow(4);
            row.Cells[1].SetCellValue(tbCollage.Text);
            row.Cells[1].CellStyle.Alignment = HorizontalAlignment.CENTER;
            row.Cells[4].SetCellValue(tbSpeciality.Text);
            row.Cells[4].CellStyle.Alignment = HorizontalAlignment.CENTER;
            row.Cells[6].SetCellValue(DateTime.Parse(tbStart.Text).ToString("D"));
            row.Cells[6].CellStyle.Alignment = HorizontalAlignment.CENTER;
            row = sheet1.GetRow(5);
            row.Cells[1].SetCellValue(ddlEduLevel.SelectedItem.Text);
            row.Cells[1].CellStyle.Alignment = HorizontalAlignment.CENTER;
            row.Cells[4].SetCellValue(ddlDegree.SelectedItem.Text);
            row.Cells[4].CellStyle.Alignment = HorizontalAlignment.CENTER;
            row.Cells[6].SetCellValue(ddlEduType.SelectedItem.Text);
            row.Cells[6].CellStyle.Alignment = HorizontalAlignment.CENTER;
            sheet1.GetRow(6).Cells[1].SetCellValue(tbEduStory.Text);
            sheet1.GetRow(6).Cells[1].CellStyle.Alignment = HorizontalAlignment.CENTER;
            sheet1.GetRow(7).Cells[1].SetCellValue(tbResearchStory.Text);
            sheet1.GetRow(7).Cells[1].CellStyle.Alignment = HorizontalAlignment.CENTER;
            sheet1.GetRow(8).Cells[1].SetCellValue(tbReason.Text);
            sheet1.GetRow(8).Cells[1].CellStyle.Alignment = HorizontalAlignment.CENTER;
            using (MemoryStream ms = new MemoryStream())
            {
                wb.Write(ms);
                byte[] data = ms.ToArray();
                HttpResponse response = System.Web.HttpContext.Current.Response;
                response.Clear();
                //Encoding pageEncode = Encoding.GetEncoding(PageEncode);
                response.Charset = "UTF-8";
                response.ContentType = "application/vnd-excel";//"application/vnd.ms-excel";
                response.AddHeader("Content-Disposition", string.Format("attachment; filename=Study.xls"));
                response.BinaryWrite(data);
            }
        }

        
        protected void gvSR_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int serial = Convert.ToInt32(e.Keys[0]);
            using (hrdbEntities ent = new hrdbEntities())
            {
                var result = from rec in ent.TKQStudyRequests where rec.SerialNO == serial select rec;
                if (result.Any())
                {
                    TKQStudyRequest record = result.Single();
                    if (record.CheckStatus == false)
                    {
                        e.Cancel = false;
                    }
                    else
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "Cannotdelete", "alert('只有未被批准的申请才可以撤销');", true);
                        e.Cancel = true;
                    }
                }
            }
        }

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            gvSR.DataBind();
        }

    }
}